﻿function FriendSite(newData) {
    this.id = ko.observable(newData.id);
    this.Name = ko.observable(newData.Name);
    this.Url = ko.observable(newData.Url);
    this.Keyword = ko.observable(newData.Keyword);
    this.SiteId = ko.observable(newData.SiteId);
}

function FriendSitesViewModel() {

    // Data
    var self = this;
    self.actualSiteId = ko.observable(data.SiteId);
    self.friendSites = ko.observableArray(data.FriendSites);
    self.newUrlText = ko.observable();
    self.newNameText = ko.observable();
    self.newKeywordText = ko.observable();
    self.fsHub = $.connection.friendSitesHub;

    // Operations
    self.addFriendSite = function () {
        self.fsHub.server.addFriendSite(data.SiteId, self.newNameText(), self.newUrlText(), self.newKeywordText());
    }

    self.fsHub.client.confirmAddFriendSite = function (fsId) {
        self.friendSites.push(new FriendSite({ id: fsId, Name: self.newNameText(), Url: self.newUrlText(), Keyword: self.newKeywordText(), SiteId: data.SiteId }));
        self.newNameText("");
        self.newUrlText("");
        self.newKeywordText("");
    }

    self.editFriendSite = function (fs) {
        self.fsHub.server.editFriendSite(fs.id, fs.Name, fs.Url, fs.Keyword);
    }

    self.removeFriendSite = function (fs) {
        self.fsHub.server.deleteFriendSite(fs.id).done(function () {
            self.friendSites.destroy(fs);
        });
    };


    //// Data
    //var self = this;
    //self.tasks = ko.observableArray([]);
    //self.newTaskText = ko.observable();
    //self.incompleteTasks = ko.computed(function () {
    //    return ko.utils.arrayFilter(self.tasks(), function (task) { return !task.isDone() && !task._destroy });
    //});

    //// Operations
    //self.addTask = function () {
    //    self.tasks.push(new Task({ title: this.newTaskText() }));
    //    self.newTaskText("");
    //};
    //self.removeTask = function (task) { self.tasks.destroy(task) };
    //self.save = function () {
    //    $.ajax("/tasks", {
    //        data: ko.toJSON({ tasks: self.tasks }),
    //        type: "post", contentType: "application/json",
    //        success: function (result) { alert(result) }
    //    });
    //};

    //// Load initial state from server, convert it to Task instances, then populate self.tasks
    //$.getJSON("/tasks", function (allData) {
    //    var mappedTasks = $.map(allData, function (item) { return new Task(item) });
    //    self.tasks(mappedTasks);
    //});
};

var fsVM = new FriendSitesViewModel();
ko.applyBindings(fsVM);

$.connection.hub.start();
